package com.longtop.framework.sys.codeInfo.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.longtop.framework.base.BaseService;
import com.longtop.framework.common.CacheUpdate;
import com.longtop.framework.common.Constant;
import com.longtop.framework.common.QueryConditions;
import com.longtop.framework.common.QueryResult;
import com.longtop.framework.security.BaseCheckedException;
import com.longtop.framework.security.SessionObject;
import com.longtop.framework.sys.codeInfo.model.TSysCodeInfo;

public class CodeInfoService extends BaseService {

	public static final String BEAN_ID = "codeInfoService";

	/**
	 * 保存、修改、删除一起做！
	 * 
	 * @param changeMap
	 *            对象列表，有三个值，删除主键列表、更新bean的列表、新增bean的列表
	 * @param sessionObject
	 * @return 操作成功受影响的记录数，有三个值，插入成功的记录数、更新成功的记录数、删除成功的记录数
	 */
	public Integer[] saveCodeInfo(Map changeMap, SessionObject sessionObject) throws BaseCheckedException {

		// 插入成功的记录数、更新成功的记录数、删除成功的记录数
		int insertCount = 0;
		int updateCount = 0;
		int deleteCount = 0;

		// 删除主键列表、更新bean的列表、新增bean的列表
		List insertBeanList = (ArrayList) changeMap.get(Constant.INSERT_BEAN_LIST);
		List updateBeanList = (ArrayList) changeMap.get(Constant.UPDATE_BEAN_LIST);
		String idList = (String) changeMap.get(Constant.ID_LIST);

		TSysCodeInfo tSysCodeInfo;
		Iterator iterator;

		// 批量插入记录
		if (insertBeanList.size() > 0) {
			iterator = insertBeanList.iterator();
			while (iterator.hasNext()) {
				tSysCodeInfo = (TSysCodeInfo) iterator.next();

				// 校验codeInfo的value是否重复。
				if (isExistCodeInfoValue(tSysCodeInfo))
					throw new BaseCheckedException("", "保存失败,代码值【" + tSysCodeInfo.getValue() + "】已经存在!");

				super.save(tSysCodeInfo);
				insertCount++;
			}
		}

		// 批量更新记录
		if (updateBeanList.size() > 0) {
			iterator = updateBeanList.iterator();
			while (iterator.hasNext()) {
				tSysCodeInfo = (TSysCodeInfo) iterator.next();

				// 校验codeInfo的value是否重复。
				if (isExistCodeInfoValue(tSysCodeInfo))
					throw new BaseCheckedException("", "保存失败,代码值【" + tSysCodeInfo.getValue() + "】已经存在!");

				super.update(tSysCodeInfo);
				updateCount++;
			}
		}

		// 批量删除记录
		if (idList.length() > 0) {
			String sql = "delete from TSysCodeInfo where codeInfoId in(" + idList + ")";
			deleteCount = super.batchUpdate(sql);
		}

		// 更新缓存：
		this.getHibernateTemplate().flush();
		CacheUpdate.getCacheUpdate().updateCodeInfoMap();

		return new Integer[] { new Integer(insertCount), new Integer(updateCount), new Integer(deleteCount) };
	}

	/**
	 * 验证此 代码信息 Id 是否存在
	 * 
	 * @param menuId
	 * @return
	 */
	private boolean isExistCodeInfoValue(TSysCodeInfo tSysCodeInfo) {
		boolean flag = false;

		String hql = "from TSysCodeInfo where codeTypeId='" + tSysCodeInfo.getCodeTypeId() + "' and value='" + tSysCodeInfo.getValue() + "'";
		if (StringUtils.isNotEmpty(tSysCodeInfo.getCodeInfoId()))
			hql = "from TSysCodeInfo where codeTypeId='" + tSysCodeInfo.getCodeTypeId() + "' and value='" + tSysCodeInfo.getValue() + "' and codeInfoId!='" + tSysCodeInfo.getCodeInfoId() + "'";

		List list = this.queryAll(hql);

		if (list.size() > 0)
			flag = true;

		return flag;
	}

	/**
	 * 依据条件，读取代码信息列表
	 * 
	 * @param queryConditions
	 *            查询条件
	 * @param pageNo
	 *            查询结果的起始页码。
	 * @param pageSize
	 *            查询结果的最大行数。如果不需要，则设置为-1
	 * @return
	 */
	public QueryResult loadCodeInfo(QueryConditions queryConditions, int pageNo, int pageSize) {

		String orderBy = "sortNo asc";
		queryConditions.setOrderBy(orderBy);

		return this.loadByConditions(queryConditions, pageNo, pageSize, TSysCodeInfo.class);
	}

	/**
	 * 读取 代码信息codeInfo , 根据<id, List<TSysCodeInfo>> 组织成一个 Map， 此方法供
	 * 系统启动时候的Listener调用。
	 * 
	 * @return 代码信息 codeInfoMap<id, List<CodeInfo>>
	 * 
	 * @author 胡砥峰
	 */
	public Map<String, List<TSysCodeInfo>> getCodeInfoMap(String codeTypeId) {

		Map codeInfoMap = new HashMap();

		// 设置查询sql语句
		String strSQL = "";
		if (StringUtils.isEmpty(codeTypeId)) {
			// 设置查询sql语句，按codeType排序
			strSQL = "from TSysCodeInfo order by codeTypeId asc, sortNo asc";
		} else {
			strSQL = "from TSysCodeInfo where codeTypeId='" + codeTypeId + "' order by codeTypeId asc, sortNo asc";
		}
		List list = this.queryAll(strSQL);

		List subList = new ArrayList();
		TSysCodeInfo tSysCodeInfo = null;
		String tmpCodeTypeId = null;
		boolean isFirst = true;

		Iterator it = list.iterator();
		while (it.hasNext()) {
			tSysCodeInfo = (TSysCodeInfo) it.next();

			if (isFirst) {
				tmpCodeTypeId = tSysCodeInfo.getCodeTypeId();
				isFirst = false;
			}

			if (!tmpCodeTypeId.equals(tSysCodeInfo.getCodeTypeId())) {
				codeInfoMap.put(tmpCodeTypeId, subList);
				subList = new ArrayList();
			}

			subList.add(tSysCodeInfo);
			tmpCodeTypeId = tSysCodeInfo.getCodeTypeId();
		}

		if (tmpCodeTypeId != null && subList.size() > 0) {
			codeInfoMap.put(tmpCodeTypeId, subList);
		}

		return codeInfoMap;
	}
}